var util = require("../../utils/util");
var config = require("../../config");

Page({
  data: {
    q: 0,  // 1 已上架，2 已借出，3 已借入，4 已还，5 我正向别人借， 6 别人正在向我借
    part: 1,
    book_list: [],
    inputShowed: false,
    inputVal: "",

    page_index: 0,
    loading: false
  },

  queryData: function (options) {
    var that = this;
    var q = options.q;
    var userInfo = getApp().globalData.userInfo;
    var my_id = userInfo.id;

    if (q == 1) {

      // 获取已上架的书
      wx.request({
        url: config.urls.someone_books,
        data: {
          id: my_id,
          ps: 10,
          pn: that.data.page_index
        },
        success: function (res) {
          console.log(res);
          if (res.data.success) {
            that.formatData(res.data.books);
            that.setData({
              book_list: that.data.book_list.concat(res.data.books),
              loading: false
            })
          }
          else {
            console.log("Book list get failed.");
          }
        }
      });
    }
    else if (q == 2) {
      // 获取已借出的书
      wx.request({
        url: config.urls.books_borrow_out,
        data: {
          id: my_id,
          ps: 10,
          pn: that.data.page_index
        },
        success: function (res) {
          console.log(res);
          if (res.data.success) {
            that.formatData(res.data.books);
            that.setData({
              book_list: that.data.book_list.concat(res.data.books),
              loading: false
            })
          }
          else {
            console.log("Book list get failed.");
          }
        }
      });
    }
    else if (q == 3) {
      // 获取已借入的书
      wx.request({
        url: config.urls.books_borrow_in,
        data: {
          id: my_id,
          ps: 10,
          pn: that.data.page_index
        },
        success: function (res) {
          console.log(res);
          if (res.data.success) {
            that.formatData(res.data.books);
            that.setData({
              book_list: that.data.book_list.concat(res.data.books),
              loading: false
            })
          }
          else {
            console.log("Book list get failed.");
          }
        }
      });
    }
    else if (q == 4) {
      // 获取已还书
      // 这个板块去掉了
    }
    else if (q == 5) {
      // 获取我向别人借书的请求
      wx.request({
        url: config.urls.applies_by_me,
        data: {
          id: my_id,
          ps: 10,
          pn: that.data.page_index
        },
        success: function (res) {
          console.log(res);
          if (res.data.success) {
            that.formatData2(res.data.book_applies);
            that.setData({
              book_list: that.data.book_list.concat(res.data.book_applies),
              loading: false,
              part: 2
            });
          }
          else {
            console.log("Book apply list get failed.");
          }
        }
      });
    }
    else if (q == 6) {
      // 获取书的请求
      wx.request({
        url: config.urls.applies_to_me,
        data: {
          id: my_id,
          ps: 10,
          pn: that.data.page_index
        },
        success: function (res) {
          console.log(res);
          if (res.data.success) {
            that.formatData2(res.data.book_applies);
            that.setData({
              book_list: that.data.book_list.concat(res.data.book_applies),
              loading: false,
              part: 2
            })
          }
          else {
            console.log("Book apply list get failed.");
          }
        }
      });
    }
  },

  onLoad: function (options) {
    var that = this;

    that.setData({
      q: options.q
    });

    that.queryData(options);
  },

  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.clearInput();
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    var that = this;
    this.setData({
      inputVal: ""
    });

    if (that.data.q == 1) {
      that.queryData({ q: 1 });
    }
    else if (that.data.q == 2) {
      that.queryData({ q: 2 });
    }
  },
  inputTyping: function (e) {
    var that = this;
    var kw = e.detail.value;
    var userInfo = getApp().globalData.userInfo;
    var my_id = userInfo.id;

    this.setData({
      inputVal: kw
    });

    if (that.data.q == 1) {
      wx.request({
        url: config.urls.search_by_name_3,
        data: {
          user_id: my_id,
          name: kw,
          ps: 10,
          pn: 0
        },
        success: function (res) {
          console.log(res);
          if (res.data.success) {
            that.formatData(res.data.books);
            that.setData({
              book_list: res.data.books
            })
          }
          else {
            console.log("search by name 3, Book list get failed.");
          }
        }
      });
    }
    else if (that.data.q == 2) {
      wx.request({
        url: config.urls.search_by_name_4,
        data: {
          user_id: my_id,
          name: kw,
          ps: 10,
          pn: 0
        },
        success: function (res) {
          console.log(res);
          if (res.data.success) {
            that.formatData(res.data.books);
            that.setData({
              book_list: res.data.books
            })
          }
          else {
            console.log("search by name 4, Book list get failed.");
          }
        }
      });
    }
  },

  editBook: function (e) {
    var book_id = e.target.id;
    console.log("book id: ", book_id);
    wx.navigateTo({
      url: '/pages/onshelf/onshelf?edit=true&id=' + book_id
    })
  },

  downShelfBook: function (e) {
    var that = this;
    var book_id = e.target.id;
    console.log("book id: ", book_id);
    var userInfo = getApp().globalData.userInfo;
    var my_id = userInfo.id;

    // 要弹出框提示确认下架
    wx.showModal({
      title: '确认下架',
      content: '请确认是否下架本书',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: config.urls.unshelve,
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              book_id: book_id,
              user_id: my_id
            },
            success: function (res) {
              if (res.data.success) {
                wx.showToast({
                  title: '下架成功',
                  icon: 'success',
                  duration: 1000
                })
                var book_list = that.data.book_list;
                // 这里应该把当前dom删除（删除数组中的一项就行了），退而求其次刷新当前页面
                for (var i = 0; i < book_list.length; i++) {
                  var book = book_list[i];
                  if (book.id == book_id) {
                    book_list.splice(i, 1);
                    break;
                  }
                }
                that.setData({
                  book_list: book_list
                });
              }
              else {
                wx.showToast({
                  title: '下架失败',
                  icon: 'loading',
                  duration: 1000
                })
                console.log("Book down shelf failed.");
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  agree: function (e) {
    var that = this;
    var apply_id = e.target.id;
    console.log("apply id: ", apply_id);
    var userInfo = getApp().globalData.userInfo;
    var my_id = userInfo.id;

    // 要弹出框提示确认借出
    wx.showModal({
      title: '确认同意借出',
      content: '请确认是否同意借出本书',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: config.urls.agree_apply,
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              apply_id: apply_id,
              my_id: my_id
            },
            success: function (res) {
              if (res.data.success) {
                wx.showToast({
                  title: '出借成功',
                  icon: 'success',
                  duration: 1000
                })
                var book_list = that.data.book_list;
                // 这里应该把当前dom删除（删除数组中的一项就行了），退而求其次刷新当前页面
                for (var i = 0; i < book_list.length; i++) {
                  var apply = book_list[i];
                  if (apply.id == apply_id) {
                    apply.status = 2;
                    break;
                  }
                }
                that.setData({
                  book_list: book_list
                });
              }
              else {
                wx.showToast({
                  title: '借出失败',
                  icon: 'loading',
                  duration: 1000
                })
                console.log("Book apply agree failed.");
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  ackBorrow: function (e) {
    var that = this;
    var apply_id = e.target.id;
    console.log("apply id: ", apply_id);
    var userInfo = getApp().globalData.userInfo;
    var my_id = userInfo.id;

    // 要弹出框提示确认已借到
    wx.showModal({
      title: '确认已借书',
      content: '请确认是否已经借到本书',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: config.urls.ack_apply,
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              apply_id: apply_id,
              my_id: my_id,
              my_name: userInfo.nickname
            },
            success: function (res) {
              if (res.data.success) {
                wx.showToast({
                  title: '借书成功',
                  icon: 'success',
                  duration: 1000
                })
                var book_list = that.data.book_list;
                // 这里应该把当前dom删除（删除数组中的一项就行了），退而求其次刷新当前页面
                for (var i = 0; i < book_list.length; i++) {
                  var apply = book_list[i];
                  if (apply.id == apply_id) {
                    book_list.splice(i, 1);
                    //记录确认已借到的事件
                    console.log(apply)
                    wx.request({
                      url: config.urls.record_borrow_action,
                      method: "POST",
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      data: {
                        event_type: "borrow_ack",
                        event_code: 2,
                        book_id: apply.book_id,
                        book_name: apply.book_name,
                        prev_borrower: -1,
                        prev_borrower_name: "",
                        borrower: userInfo.id,
                        borrower_name: userInfo.nickname,
                        action_city: config.city_code.ChengDu
                      },
                      success: function (res) {
                        if (res.data.success) {
                          console.log("记录了已借到事件")
                          console.log(res)
                        } else {
                          console.log("record borrow_ack book failed");
                        }
                      }
                    });
                    break;
                  }
                }
                that.setData({
                  book_list: book_list
                });
              }
              else {
                wx.showToast({
                  title: '借书失败',
                  icon: 'loading',
                  duration: 1000
                })
                console.log("Book apply ack failed.");
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  applyReturn: function (e) {
    var that = this;
    var book_id = e.target.id;
    console.log("book id: ", book_id);
    var userInfo = getApp().globalData.userInfo;
    var my_id = userInfo.id;

    // 要弹出框提示确认下架
    wx.showModal({
      title: '确认还书',
      content: '请确认是否要归还本书',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: config.urls.apply_ret,
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              book_id: book_id,
              my_id: my_id
            },
            success: function (res) {
              if (res.data.success) {
                wx.showToast({
                  title: '申请还书成功',
                  icon: 'success',
                  duration: 1000
                })
                var book_list = that.data.book_list;

                for (var i = 0; i < book_list.length; i++) {
                  var book = book_list[i];
                  if (book.id == book_id) {
                    book.status = 4;
                    break;
                  }
                }
                that.setData({
                  book_list: book_list
                });
              }
              else {
                wx.showToast({
                  title: '还书失败',
                  icon: 'loading',
                  duration: 1000
                })
                console.log("Book apply return failed.");
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  ackRet: function (e) {
    var that = this;
    var book_id = e.target.id;
    console.log("book id: ", book_id);
    var userInfo = getApp().globalData.userInfo;
    var my_id = userInfo.id;

    // 要弹出框提示确认下架
    wx.showModal({
      title: '确认已还书',
      content: '请确认借阅者是否已归还本书',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: config.urls.ack_ret,
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              book_id: book_id,
              my_id: my_id
            },
            success: function (res) {
              if (res.data.success) {
                wx.showToast({
                  title: '还书成功',
                  icon: 'success',
                  duration: 1000
                })
                var book_list = that.data.book_list;
                for (var i = 0; i < book_list.length; i++) {
                  var book = book_list[i];
                  if (book.id == book_id) {
                    book_list.splice(i, 1);
                    console.log(book)
                    //记录确认已归还的事件
                    wx.request({
                      url: config.urls.record_borrow_action,
                      method: "POST",
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      data: {
                        event_type: "return_ack",
                        event_code: 4,
                        book_id: book.id,
                        book_name: book.name,
                        prev_borrower: -1,
                        prev_borrower_name: "",
                        borrower: book.borrower,
                        borrower_name: book.borrower_name,
                        action_city: config.city_code.ChengDu
                      },
                      success: function (res) {
                        if (res.data.success) {
                          console.log("记录了已归还事件")
                          console.log(res)
                        } else {
                          console.log("record return_ack book failed");
                        }
                      }
                    });
                    break;
                  }
                }
                that.setData({
                  book_list: book_list
                });
              }
              else {
                wx.showToast({
                  title: '还书失败',
                  icon: 'loading',
                  duration: 1000
                })
                console.log("Book apply return failed.");
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  removeApply: function (e) {
    var that = this;
    var ba_id = e.target.id;
    console.log("ba id: ", ba_id);
    var userInfo = getApp().globalData.userInfo;
    var my_id = userInfo.id;

    // 弹出框提示
    wx.showModal({
      title: '确认删除借书申请',
      content: '请确认是否删除这个借书申请',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: config.urls.removeApply,
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              apply_id: ba_id,
              my_id: my_id
            },
            success: function (res) {
              if (res.data.success) {
                var book_list = that.data.book_list;
                for (var i = 0; i < book_list.length; i++) {
                  var book = book_list[i];
                  if (book.id == ba_id) {
                    book_list.splice(i, 1);
                    break;
                  }
                }
                that.setData({
                  book_list: book_list
                });
              }
              else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'loading',
                  duration: 1000
                })
                console.log("Book apply remove failed.");
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  takeNote: function (e) {
    var that = this;
    var book_id = e.target.id;
    wx.navigateTo({
      url: '/pages/takenote/takenote?book_id=' + book_id
    })
  },

  onReachBottom: function () {
    console.log("event onReachBottom")
    var that = this;

    if (!that.data.loading) {
      var books = that.data.book_list;
      console.log(books.length % 10)
      // 一次加载10个，如果是10的倍数才继续加载
      if (books.length > 0 && books.length % 10 == 0) {
        that.data.page_index++;
        that.data.loading = true;
        that.queryData({q: that.data.q});
      }
      else {
        // 否则不做任何事
        console.log("do nothing")
      }
    }
  },

  formatData: function (data) {
    for (var i = 0; i < data.length; i++) {
      var item = data[i];
      item.putaway_time = util.fds(item.putaway_time);
      if (item.borrower_name == "") {
        item.borrower_name = "无";
      }
      if (item.borrow_time == -1) {
        item.borrow_time = "无";
      }
      else {
        item.borrow_time = util.fds(item.borrow_time);
      }
    }
  },

  formatData2: function (data) {
    for (var i = 0; i < data.length; i++) {
      var item = data[i];
      item.apply_time = util.fds(item.apply_time);
    }
  }
});
